package com.longge;

import java.util.*;

/**
 * @program: my-code
 * @description:
 * @author: longge
 * @create: 2021-04-14 00:40
 */
public class ListOfDepth {

    int d = 0;
    TreeMap<Integer, ListNode> curMap = new TreeMap<>();

    public ListNode[] listOfDepth(TreeNode tree) {
        TreeMap<Integer, ListNode> map = new TreeMap<>();
        dfs(tree, map);
        return map.values().toArray(new ListNode[]{});
    }

    private void dfs(TreeNode tree, TreeMap<Integer, ListNode> map) {
        if (tree == null) return;
        d++;
        ListNode node = map.get(d);
        if (node == null) {
            node = new ListNode(tree.val);
            map.put(d, node);
            curMap.put(d, node);
        } else {
            ListNode cur = curMap.get(d);
            cur.next = new ListNode(tree.val);
            cur = cur.next;
            curMap.put(d, cur);
        }
        dfs(tree.left, map);
        dfs(tree.right, map);
        d--;
    }
}
